
package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断是否为登录请求
        if (request.getURI().getPath().contains("login")){
            //直接放行
            return chain.filter(exchange);
        }
        //
        String token = request.getHeaders().getFirst("token");
        //3.验证是否有token
        if (StringUtils.isBlank(token)){
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4.验证token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //验证是否过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2){
                //返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.setComplete();
            }

            //解析出token中的原始数据：当前登录用户id
            Object userId = claimsBody.get("id");

            // 往下游微服务路由时追加请求头：userId = 当前登录用户id
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();

            //重置header
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //5.放行
        return chain.filter(exchange);
    }



    /* 优先级设置  值越小  优先级越高
     * @return
     */


    @Override
    public int getOrder() {
        return 0;
    }
}